package org.little.test.controller;

import org.little.test.model.Books;
import org.little.test.repository.BooksRepository;
import org.little.test.service.BookService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * Created by liuhongtao on 2017/7/17.
 */

//@RestController
@Controller
public class BookController {

    @Autowired
    private BookService bookService;
    @Autowired
    private BooksRepository booksRepository;
    private static final Logger LOG = LoggerFactory.getLogger(BookController.class);

    @RequestMapping("/test")
    public String test() {
        return "test";
    }


    @RequestMapping("/list")
    public String list() {
        return "list";
    }

    @RequestMapping("/create")
    public String create(HttpServletRequest request,Map<String,Object> model) {
        String type = request.getParameter("type");
        if("show".equals(type)){
            String id = request.getParameter("id");
            Books bs = booksRepository.getOne(Long.parseLong(id));
            model.put("bs",bs);
        }else{

        }
        return "create";
    }

    @RequestMapping("/save")
    public String save(HttpServletRequest request) {

        String id = request.getParameter("id");
        String bookEditor = request.getParameter("bookEditor");
        String press = request.getParameter("press");
        String price = request.getParameter("price");
        String authorAbout = request.getParameter("authorAbout");
        String outline = request.getParameter("outline");
        String contentIntroduction = request.getParameter("contentIntroduction");
        String bookName = request.getParameter("bookName");
        Books bs = new Books();
        if (!StringUtils.isEmpty(id)) {
            bs = booksRepository.getOne(Long.parseLong(id));
//            bs.setId(bs.getId());
        }else{
            bs.setCreateTime(new Date());
        }
        bs.setBookEditor(bookEditor);
        bs.setPress(press);
        bs.setPrice(Double.parseDouble(price));
        bs.setAuthorAbout(authorAbout);
        bs.setOutline(outline);
        bs.setContentIntroduction(contentIntroduction);
        bs.setBookName(bookName);

        bs.setUpdateTime(new Date());
        bs.setUpdateTimeLong(new Date().getTime());

        bookService.doSaveBook(bs);
//        return new ModelAndView("redirect:/toList");
        return "redirect:/list ";
    }
}
